<template>
  <HeaderSearch></HeaderSearch>
  <headerMenu :is-search-product="true"></headerMenu>

  <!--End Menu End-->
  <div class="i_bg">
    <div class="content mar_20">
      <img src="/images/img2.jpg" />
    </div>

    <!--Begin 第二步：确认订单信息 Begin -->
    <div class="content mar_20">
      <div class="two_bg">
        <div class="two_t">
          <span class="fr"></span>商品列表
        </div>
        <table border="0" class="car_tab" style="width:1110px;" cellspacing="0" cellpadding="0">
          <tbody>
            <tr>
              <td class="car_th" width="550">商品名称</td>
              <td class="car_th" width="150">购买数量</td>
              <td class="car_th" width="130">小计</td>
            </tr>
            <tr v-for="(product, index) in productList">
              <td>
                <div class="c_s_img"><img :src="url + product.fileName" width="73" height="73" /></div>
                {{ product.name }}
              </td>

              <td align="center">{{ product.quantity }}</td>
              <td align="center" style="color:#ff4e00;">￥{{ product.price * product.quantity }}</td>
            </tr>
          </tbody>
        </table>

        <div class="two_t">
          <span class="fr"></span>收货人信息
          <span class="fr"><a @click.prevent="chooseUserAddress()" >选择其他地址</a></span>
          <span class="fr" v-if="address.length!=0"> <a @click.prevent="updateUserAddress()"  >修改收货人信息</a>&nbsp;&nbsp;</span>
        </div>
        <table border="0" class="peo_tab" style="width:1110px;" cellspacing="0" cellpadding="0">
          <tbody>
            <tr>
              <td class="p_td" width="160">收件人</td>
              <td width="395">{{ address.name }}</td>
              <td class="p_td" width="160">收件人电话</td>
              <td>{{ address.phone }}</td>
            </tr>
            <tr>
              <td class="p_td"> <label>收货地址：</label></td>
              <td width="395">{{ formatAddress(address.address) }}</td>
               <!-- <td>
               <select>
                <option selected>{{ formatAddress(address.address) }}</option>
                <option v-for="address1 in addressList" v-if="address.isDefault!=1">{{ formatAddress(address1.address) }}</option>
               </select>
              </td> -->
            </tr>
          </tbody>
        </table>


        <div class="two_t">
          支付方式
        </div>
        <ul class="pay">
          <li :class="{ checked: selectedPayment === '支付宝' }" @click="selectPayment('支付宝')">支付宝<div class="ch_img">
            </div>
          </li>
          <li :class="{ checked: selectedPayment === '微信' }" @click="selectPayment('微信')">微信付款<div class="ch_img"></div>
          </li>
        </ul>



        <table border="0" style="width:900px; margin-top:20px;" cellspacing="0" cellpadding="0">
          <tbody>
            <tr height="70">
              <td align="right">
                <b style="font-size:14px;">应付款金额：<span style="font-size:22px; color:#ff4e00;">￥{{ cost }}</span></b>
              </td>
            </tr>
            <tr height="70">
              <td align="right"><a @click.prevent="pay3()"><img src="/images/btn_sure.gif" /></a></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <!--End 第二步：确认订单信息 End-->

  </div>


</template>


<script setup>
import { onMounted, ref, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import store from '@/store'
import HeaderSearch from '@/components/HeaderSearch.vue'
import HeaderMenu from '@/components/HeaderMenu.vue'

const router = useRouter()
const cost = ref(0)
const conut = ref(0)
const idefault = ref(false)
const productList = ref([])
const address = ref([])
const addressList = ref({})

const userId = window.sessionStorage.getItem('id')
const loginName = window.sessionStorage.getItem('loginName')
const url = "http://192.168.12.159:83/"
const selectedPayment = ref('支付宝')
// 选择支付方式的方法
const selectPayment = (payment) => {
  selectedPayment.value = payment
}
//得到购物车的商品
const getProduct = async () => {
  if (userId == null) {
    return;
  }
  try {
    const request = await axios.get("/api/getProductForPayCar", {
      params: {
        userId: userId
      }
    })
    productList.value = request.data.productList;
    cost.value = 0;
    conut.value = 0;
    for (let i = 0; i < productList.value.length; i++) {
      cost.value += productList.value[i].price * productList.value[i].quantity;
      conut.value += productList.value[i].quantity;
    }


  } catch (error) {
    console.error('商品获取失败:', error)
  }

}


//获取用户收货地址
const getAddress = async () => {
  try {
    const response = await axios.get('/api/getUserAddressList?userId=' + userId)
    addressList.value = response.data.userAddressList


    for (let deAddress of addressList.value) {
      if (deAddress.isDefault == 1) {
        address.value = deAddress
        idefault.value = true
        break;
      }
    }
    
    console.log("address",address.value);
    
    if (!idefault.value) {
      alert('请添加用户中心添加默认收货地址')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

//更改收件人信息
const updateUserAddress = async () => {
  router.push({
    path: '/updateAddress',
    query: {
      id: address.value.id
    }
  })
}
// 检查地址更新
const checkAddressUpdate = () => {
  getUser()
  getAddress()

}

// 格式化地址显示
function formatAddress(address) {
  if (!address || !address.length) return '';
  const parts = address.split(' ');
  if (parts.length >= 3) {
    // 按照规范添加完整后缀
    return parts[0] + "省" + parts[1] + "市" + parts[2] + "区" + (parts[3] || '');
  }
  return address;
}



//继续支付
const pay3 = async () => {
  if (!idefault.value) {
    alert('请添加用户中心添加默认收货地址')
    return
  }
console.log("payment",selectedPayment.value);

  let serialNumber = null;
  try {
    const require = await axios.post('/api/addOrder', {
      products: productList.value,
      payMent: selectedPayment.value,
      phone: address.value.phone,
      name : address.value.name
    })
    if (require.data.code == 5500) {
      alert("添加失败," + require.data.reason);
    } else {
      serialNumber = require.data.serialNumber;
    }
  } catch (error) {
    console.error('添加数据失败:', error)
  }


  router.push({
    path: '/buyCar_Three',
    query: {
      serialNumber: serialNumber,
      address: formatAddress(address.value.address),
      cost: cost.value,
      payName: selectedPayment.value
    }
  })

}

const chooseUserAddress = async () => {
  router.push({
    path: '/addressList'
  })
} 
// 进入管理页面时隐藏HeaderView
onMounted(() => {

  getAddress()
  getProduct()
  store.commit('setShowPage', 1)

  window.addEventListener('addressUpdated', checkAddressUpdate)
})


// 离开管理页面时恢复HeaderView
onUnmounted(() => {
  store.commit('setShowPage', 0)

  window.removeEventListener('addressUpdated', checkAddressUpdate)

})

</script>

<style></style>